/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.db.bean.Posts;
import edu.cmu.fithub.formbeans.GroupForm;
import edu.cmu.fithub.formbeans.PostForm;

public class CreateUserPostAction extends Action {

	private static final String USER_POSTS = "user";
	private static final String GROUP_POSTS = "group";
	private FormBeanFactory<PostForm> formFactory = FormBeanFactory
			.getInstance(PostForm.class);

	public CreateUserPostAction() {
	}

	public String getName() {
		return "createUserPost.do";
	}

	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		String postType = request.getParameter("postType");
		String groupId = request.getParameter("groupId");
		if (postType == null || postType.length() == 0) {
			errors.add("Post Type cannot be null");
		} else if (groupId == null || groupId.length() == 0) {
			errors.add("Group ID cannot be null");
		}
		if(errors.size() > 0) {
			// cannot send to add post page since post type and group id is
			// invalid
			return "error.jsp";
		}
		try {
			Posts posts = new Posts();
			User user = (User) request.getSession().getAttribute("user");
			PostForm postForm = formFactory.create(request);
			errors.addAll(postForm.getValidationErrors());
			if (errors.size() == 0) {
				posts.setPost(postForm.getPost());
				posts.setPostType(postType);
				posts.setGroupId(Integer.parseInt(groupId));
				posts.setDate(new Date());
				posts.setUser(user);
				Session dbSession = DBHelper.getSessionFactory().openSession();
				dbSession.beginTransaction();
				dbSession.save(posts);
				dbSession.getTransaction().commit();
			} else {
				return "showStory.do?postType=" + postType + "&groupId="
						+ groupId;
			}
		} catch (FormBeanException e) {
			errors.add(e.toString());
			return "error.jsp";
		} catch (NumberFormatException e) {
			errors.add(e.toString());
			return "error.jsp";
		}
		return "storysuccess.jsp";
	}
}
